package sample.config;

/*
 * @author ding
 * @date 2022/1/19 09:42:44
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import sample.entity.SysResource;
import sample.entity.SysRole;
import sample.entity.User;
import sample.service.SysResourceService;
import sample.service.SysRoleService;
import sample.service.UserService;

import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class CustomerUserDetailsService implements UserDetailsService {
	@Autowired
	UserService userService;
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private SysResourceService resourceService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.queryByUsername(username);
		if (user == null) {
			throw new UsernameNotFoundException(username + "  没找到该用户");
		}
		List<SysRole> roleList = roleService.queryByUid(user.getId());
		List<SysResource> resourceList = resourceService.queryByUid(user.getId());
		ArrayList<GrantedAuthority> authorities = new ArrayList<>();
		for (SysRole sysRole : roleList) {
			authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRole.getCode()));
		}
		for (SysResource sysResource : resourceList) {
			authorities.add(new SimpleGrantedAuthority(sysResource.getCode()));
		}


		return new org.springframework.security.core.userdetails.User(username, user.getPassword(), authorities);
	}
}
